package com.dff.ytsdkkit;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.tencent.youtu.sdkkit.YtSDKKit;
import com.tencent.youtu.sdkkit.ytselectimage.SelectPictureActivity;
import com.tencent.youtu.sdkkitframework.common.FileUtils;
import com.tencent.youtu.sdkkitframework.common.YtLogger;
import com.tencent.youtu.sdkkitframework.framework.YtSDKKitFramework;
import com.tencent.ytcommon.util.YTCommonInterface;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;


public class MainActivity extends Activity {

    public interface IMainActivity{
        void result(byte[] image);
    }

    private static IMainActivity iMainActivity;

    public static void setiMainActivity(IMainActivity iMainActivity) {
        MainActivity.iMainActivity = iMainActivity;
    }

    private static final String TAG = "MainActivity";
    private TextView lightLiveCheckBtn;

    //防止连续点击
    private boolean isShowedActivity = false;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_yt);
        FileUtils.loadLibrary("opencv_tinyworld");
        FileUtils.loadLibrary("YTCommon");
        int r = YTCommonInterface.initAuth(getApplicationContext(),"FaceSDK.license",0);
        if (r != 0)
        {
            Log.e(TAG, "Auth failed" + r);
        }
        init();

        String sdkJsonPath = "configs/YtSDKSettings.json";
        String uiJsonPath = "configs/YtSDKUIConfig.json";

        try {
            String sdkContent = FileUtils.readAssetFile(getBaseContext(),sdkJsonPath).toString();
            String uiContent = FileUtils.readAssetFile(getBaseContext(),uiJsonPath).toString();

            YtSDKKit.getInstance().initWithConfig(sdkContent, uiContent);
        } catch(Exception e)
        {
            Log.e(TAG, "SDKPath:" + sdkJsonPath);
            Log.e(TAG, e.getMessage());
        }
    }

    private void popTip(final String msg, final String title) {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(title)
                        .setMessage(msg)
                        .show();
            }
        });
    }
    private void popTip(final String msg, final String title, final Bitmap bitmap) {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                LayoutInflater inflater = getLayoutInflater();
                View dialogLayout = inflater.inflate(R.layout.alertdialog_yt, null);

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                final AlertDialog dialog = builder.create();
                dialog.setView(dialogLayout);

                dialog.setTitle(title);
                dialog.setMessage(msg);

                dialog.show();
                ImageView image = (ImageView) dialog.findViewById(R.id.dialog_image_view);
                image.setImageBitmap(bitmap);

            }
        });
    }

    private void init() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //光线活体
        findViewById(R.id.actovoty_main_ty_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> permissions = new ArrayList();
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_PHONE_STATE)) {
                    permissions.add(android.Manifest.permission.READ_PHONE_STATE);
                }
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA)) {
                    permissions.add(android.Manifest.permission.CAMERA);
                }
                if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                if (permissions.size() > 0) {
                    String[] perms = new String[permissions.size()];
                    ActivityCompat.requestPermissions(MainActivity.this, permissions.toArray(perms), PERMISSON_REQUESTCODE);
                } else {
                    start();
                }
            }
        });
        //静默活体
        findViewById(R.id.silentDetectBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowedActivity) {
                    isShowedActivity = true;
                    //弹出界面
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_SILENT_LIVENESS, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
                            String cmp = ((String)resultDict.get("extra"));
                            String info = (String)resultDict.get("info");
                            try {
                                JSONObject obj = new JSONObject(info);
                                if (obj.has("best_image")) {
                                    obj.remove("best_image");
                                }
                                if (obj.has("compare_image")) {
                                    obj.remove("compare_image");
                                }
                                info = obj.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            popTip(info + (cmp==null?"":cmp), "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            popTip(message, "识别失败");
                        }
                    });
                }
            }
        });
        //动作检测
        findViewById(R.id.poseDetectBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowedActivity) {
                    isShowedActivity = true;
                    //弹出界面
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_ACTION_LIVENESS, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
                            String cmp = ((String)resultDict.get("extra"));
                            String info = (String)resultDict.get("info");
                            try {
                                JSONObject obj = new JSONObject(info);
                                if (obj.has("best_image")) {
                                    obj.remove("best_image");
                                }
                                if (obj.has("compare_image")) {
                                    obj.remove("compare_image");
                                }
                                info = obj.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            popTip(info + (cmp==null?"":cmp), "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            popTip(message, "识别失败");
                        }
                    });
                }
            }
        });
//        //动作反光检测
        findViewById(R.id.poseReflectDetectBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowedActivity) {
                    isShowedActivity = true;
                    //弹出界面
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_ACTREFLECT_LIVENESS, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
                            String cmp = ((String)resultDict.get("extra"));
                            String info = (String)resultDict.get("info");
                            try {
                                JSONObject obj = new JSONObject(info);
                                if (obj.has("best_image")) {
                                    obj.remove("best_image");
                                }
                                if (obj.has("compare_image")) {
                                    obj.remove("compare_image");
                                }
                                info = obj.toString();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            popTip(info + (cmp==null?"":cmp), "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            popTip(message, "识别失败");
                        }
                    });
                }
            }
        });
        //录入对比源
        findViewById(R.id.selectPictureBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("请选择\"单人、高清、无遮挡的正面人脸\"照片作为比对源")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (!isShowedActivity) {
                                    isShowedActivity = true;
                                    //弹出界面
                                    Intent intent = new Intent();
                                    Activity activity = MainActivity.this;
                                    intent.setClass(activity, SelectPictureActivity.class);
                                    activity.startActivity(intent);
                                }
                            }
                        })
                        .show();
            }
        });
        //银行卡ocr
        findViewById(R.id.ocrbankcardBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowedActivity) {
                    isShowedActivity = true;
                    JSONObject sdkJsonObject = YtSDKKit.getInstance().getSDKConfig(YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR);
                    try {
                        sdkJsonObject.put("ocrtype", "creditcard");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    YtSDKKit.getInstance().setSDKConfig(YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR, sdkJsonObject);
                    //弹出界面
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
                            Log.d(TAG, "on Process succeed " + resultDict.get("info"));
                            String cardid = null;
                            try {
                                JSONObject obj = new JSONObject((String)resultDict.get("info"));
                                JSONArray jsonArray = obj.getJSONArray("items");
                                for (int i = 0; i < jsonArray.length(); ++i)
                                {
                                    if (jsonArray.getJSONObject(i).getString("item").equals("卡号"))
                                    {
                                        cardid = jsonArray.getJSONObject(i).getString("itemstring");
                                        break;
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            popTip("id:" + cardid, "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            popTip(message, "识别失败");
                        }
                    });
                }
            }
        });
        //身份证ocr
        findViewById(R.id.ocridcardBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowedActivity) {
                    isShowedActivity = true;
                    JSONObject sdkJsonObject = YtSDKKit.getInstance().getSDKConfig(YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR);
                    try {
                        sdkJsonObject.put("ocrtype", "idcard");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    YtSDKKit.getInstance().setSDKConfig(YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR, sdkJsonObject);
                    //弹出界面
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_OCR, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
//                            Log.d(TAG, "on Process succeed " + resultDict.get("info"));
                            String name = null, cardid = null, addr = null;
                            try {
                                JSONObject obj = new JSONObject((String)resultDict.get("info"));
                                name = obj.getString("name");
                                cardid = obj.getString("id");
                                addr = obj.getString("address");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            popTip("姓名:" + name + "\nid:" + cardid + "\n地址:" + addr, "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            popTip(message, "识别失败");
                        }
                    });
                }
            }
        });
        //唇语读取
        findViewById(R.id.lipReadingBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isShowedActivity){
                    isShowedActivity = true;
                    YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_LIP_READ, new YtSDKKit.IYtSDKKitResultListener() {
                        @Override
                        public void onProcessSucceed(HashMap<String, Object> resultDict) {
                            Log.d(TAG, "on Process succeed " + resultDict.get("info"));
                            String cmp = ((String)resultDict.get("extra"));
                            String info = (String)resultDict.get("info");
                            try {
                                JSONObject obj = new JSONObject(info);
                                if (obj.has("best_image")) {
                                    obj.remove("best_image");
                                }
                                if (obj.has("compare_image")) {
                                    obj.remove("compare_image");
                                }
                                if (obj.has("compare_photo")) {
                                    obj.remove("compare_photo");
                                }
                                info = obj.toString();
                                info = info.substring(0, Math.min(info.length(), 256));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            YuvImage bestImage = (YuvImage)resultDict.get("best_image");
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            bestImage.compressToJpeg(new Rect(0, 0, bestImage.getWidth(), bestImage.getHeight()), 90, stream);
                            Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
                            popTip(info + (cmp==null?"":cmp), "识别通过");
                        }

                        @Override
                        public void onProcessFailed(int errorCode, String message) {
                            Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                            int min = Math.min(message.length(), 1024);
                            popTip(message.substring(0, min), "识别失败");
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowedActivity = false;
    }
    public void sendNetworkRequest(final String url, final String requestContent, final HashMap<String, String> requestHeader, final YtSDKKitFramework.IYtSDKKitNetResponseParser parser) {
        (new Thread(new Runnable() {
            public void run() {
                try {
                    URL requestUrl = new URL(url);
                    HttpsURLConnection conn = (HttpsURLConnection)requestUrl.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(YtSDKKitFramework.getInstance().getNetworkRequestTimeoutMS());
                    if (requestHeader != null) {
                        Iterator var3 = requestHeader.entrySet().iterator();

                        while(var3.hasNext()) {
                            Entry<String, String> entry = (Entry)var3.next();
                            conn.addRequestProperty((String)entry.getKey(), (String)entry.getValue());
                        }
                    }

                    OutputStream os = conn.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(requestContent);
                    writer.flush();
                    writer.close();
                    os.close();
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuffer sb = new StringBuffer("");
                        String line = "";
                        if ((line = in.readLine()) != null) {
                            sb.append(line);
                        }

                        in.close();
                        HashMap<String, String> responseMap = new HashMap();
                        responseMap.put("response", sb.toString());
                        parser.onNetworkResponseEvent(responseMap, (Exception)null);
                    } else {
                        YtLogger.e(TAG, "Network response failed " + responseCode);
                        parser.onNetworkResponseEvent((HashMap)null, new Exception("Https Response Failed with code:" + responseCode));
                    }
                } catch (IOException var10) {
                    YtLogger.e(TAG, "Network response failed " + var10.getLocalizedMessage());
                    parser.onNetworkResponseEvent((HashMap)null, var10);
                }

            }
        })).start();
    }


    private static final int PERMISSON_REQUESTCODE = 1;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (PERMISSON_REQUESTCODE == requestCode) {
            boolean flag = true;
            for (int i = 0; i < permissions.length; i++) {
                if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                Toast.makeText(MainActivity.this,"权限被拒绝",Toast.LENGTH_LONG).show();
            } else {
                start();
            }
        }
    }

    private void start(){
        if (!isShowedActivity) {
            isShowedActivity = true;
//                    YtSDKKit.getInstance().setCurrentNetworkListener(new YtSDKKit.IYtSDKKitNetworkListener() {
//                        @Override
//                        public void onNetworkHandle(String s, String s1, HashMap<String, String> hashMap, YtSDKKitFramework.IYtSDKKitNetResponseParser iYtSDKKitNetResponseParser) {
//                            sendNetworkRequest(s, s1, hashMap, iYtSDKKitNetResponseParser);
//                        }
//                    });
            //弹出界面
            YtSDKKit.getInstance().startProcesssWith(getApplicationContext(), YtSDKKit.YtSDKKitWorkMode.YT_SDK_WM_REFLECT_LIVENESS, new YtSDKKit.IYtSDKKitResultListener() {
                @Override
                public void onProcessSucceed(HashMap<String, Object> resultDict) {
                    String cmp = ((String)resultDict.get("extra"));
                    Log.d(TAG,cmp);
                    String info = (String)resultDict.get("info");
                    Log.d(TAG,info);
                    try {
                        JSONObject obj = new JSONObject(info);
                        if (obj.has("best_image")) {
                            obj.remove("best_image");
                        }
                        if (obj.has("compare_image")) {
                            obj.remove("compare_image");
                        }
                        info = obj.toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    YuvImage bestImage = (YuvImage)resultDict.get("best_image");
//                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                            bestImage.compressToJpeg(new Rect(0, 0, bestImage.getWidth(), bestImage.getHeight()), 90, stream);
//                            Bitmap bmp = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
//                            popTip(info + (cmp==null?"":cmp), "识别通过",bmp);
                    if(iMainActivity!=null){
                        iMainActivity.result(bestImage.getYuvData());
                    }
                    finish();
                }

                @Override
                public void onProcessFailed(int errorCode, String message) {
                    Log.d(TAG, "on Process failed code:" + errorCode + " msg:" + message);
                    popTip(message, "识别失败");
                }
            });
        }
    }
}
